
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Canvas Drawing and Download</title>
<style>
  canvas {
    border: 1px solid black;
  }
</style>
</head>
<body>
<canvas id="myCanvas" width="300" height="300"></canvas>
<button onclick="downloadCanvas()">下载图片</button>

<script>
function drawCanvas() {
  const canvas = document.getElementById('myCanvas');
  const ctx = canvas.getContext('2d');

  // 清除画布
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 绘制圆形
  const radius = 100;
  ctx.beginPath();
  ctx.arc(canvas.width / 2, canvas.height / 2, radius, 0, Math.PI * 2);
  ctx.strokeStyle = 'blue';
  ctx.lineWidth = 5;
  ctx.stroke();

  // 绘制三角形
  ctx.beginPath();
  const centerX = canvas.width / 2;
  const centerY = canvas.height / 2;
  const triangleSize = 50;
  ctx.moveTo(centerX, centerY - triangleSize);
  ctx.lineTo(centerX + triangleSize * Math.sqrt(3) / 2, centerY + triangleSize / 2);
  ctx.lineTo(centerX - triangleSize * Math.sqrt(3) / 2, centerY + triangleSize / 2);
  ctx.closePath();
  ctx.fillStyle = 'red';
  ctx.fill();
}

function downloadCanvas() {
  const canvas = document.getElementById('myCanvas');
  const url = canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream');
  const link = document.createElement('a');
  link.href = url;
  link.download = 'drawing.png';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

drawCanvas(); // 初始化绘制
</script>
</body>
</html>